<template>
  <div class="good-tabs">
    <el-form
      :model="formData"
      :rules="formRules"
      label-position="top"
      ref="formRef"
    >
      <el-tabs
        v-model="index"
        tab-position="left"
        @tab-click="handleTabClick(index)"
        :before-leave="beforeActive"
      >
        <el-tab-pane
          v-for="(item, i) in labels"
          :label="item"
          :key="item"
          :name="i + ''"
        >
          <!-- 第一个tab的内容 -->
          <div v-if="item == '基本信息'">
            <el-form-item
              v-for="(item2, ii) in firstItemLabels"
              :key="item2"
              :label="item2"
              :prop="getPropNames(ii)"
            >
              <el-input v-model="formData[getPropNames(ii)]"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                :options="casData"
                :props="casProps"
                v-model="formData.selectedCates"
                @change="handlechange"
              ></el-cascader>
            </el-form-item>
          </div>
          <!-- 第二个tab的内容 -->
          <div v-if="item == '商品参数'">
            <el-form-item
              v-for="item in tab2Data"
              :key="item.attr_name"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(item2, i) in item.attr_vals"
                  :key="i"
                  :label="item2"
                  border
                  size="mini"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
          <!-- 第三个tab -->
          <div v-if="item == '商品属性'">
            <el-form-item
              v-for="item2 in tab3Data"
              :label="item2.attr_name"
              :key="item2.attr_id"
            >
              <el-input v-model="item2.attr_vals"></el-input>
            </el-form-item>
          </div>
          <!-- 第四个tab -->
          <div v-if="item == '商品图片'">
            <!-- 这里需要指定一个头部 由于这个upload自己调用ajax请求 并没有使用axios 所以axios无法给其token -->
            <el-upload
              :headers="headerConfig"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              list-type="picture"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :on-preview="handlePreview"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </div>
          <!-- 第五个 -->
          <div v-if="item == '商品内容'">
            <el-form-item label="描述" class="desc">
              <el-input
                type="textarea"
                :rows="8"
                placeholder="请输入商品描述"
                v-model="formData.goods_introduce"
              >
              </el-input>
              <el-button type="primary" class="add-good" @click="addGood"
                >添加商品</el-button
              >
            </el-form-item>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <!-- 图片预览的对话框 -->
    <el-dialog :visible.sync="previewVisible">
      <h2 style="margin-bottom:10px;">图片预览</h2>
      <img :src="previewPath" style="width:100%;" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "goodTabs",
  data() {
    return {
      index: this.activeIndex,
      firstItemLabels: ["商品名称", "商品价格", "商品重量", "商品数量"],

      tab2Data: [], //第二个tab所需要的数据 many数据
      tab3Data: [], // only数据

      //图片上传 给其token
      headerConfig: {
        Authorization: sessionStorage.getItem("token")
      },
      //图片上传后在服务器的路径

      previewPath: "",
      previewVisible: false,
      goodDes: ""
    };
  },
  // watch: {
  //   index(newValue) {
  //     console.log(newValue)
  //     this.activeIndex = newValue
  //     console.log(this.activeIndex)
  //   }
  // },
  methods: {
    getPropNames(ii) {
      let a = [];
      for (let i in this.formRules) {
        a.push(i);
      }
      return a[ii];
    },
    //判断是否选择了三级分类
    handlechange() {
      // console.log(this.formData.selectedCates);
      if (this.formData.selectedCates.length != 3) {
        this.formData.selectedCates = [];
        this.$message.error("请选择三级分类");
      }
    },
    //在切换标签的时候进行判断 看是否符合条件
    beforeActive(active, oldactive) {
      //当处在第一个标签的时候,如果没有选中三级分类 则不能切换
      if (this.formData.selectedCates.length != 3 && oldactive == "0") {
        this.$message.error("请选择三级分类");
        return false;
      }
    },
    handleTabClick(index) {
      // 首先是发射出去  让父组件的activeIndex修改
      this.$emit("update:activeIndex", index);
      //根据点击的name来处理不同的事件
      if (index == "1") {
        //id是 三级分类的id 前面做了处理 只有有三级分类 才能点击其它tab
        this.$http
          .get(`categories/${this.formData.selectedCates[2]}/attributes`, {
            params: {
              sel: "many"
            }
          })
          .then(res => {
            if (res.data.meta.status == 200) {
              // let temp = []
              res.data.data.forEach(item => {
                item.attr_vals = item.attr_vals
                  ? item.attr_vals.split(" ")
                  : [];
              });
              this.tab2Data = res.data.data;
              console.log(this.tab2Data);
            } else {
              this.$message.error("获取失败");
              return;
            }
          })
          .catch(err => err);
      } else if (index == "2") {
        this.$http
          .get(`categories/${this.formData.selectedCates[2]}/attributes`, {
            params: {
              sel: "only"
            }
          })
          .then(res => {
            if (res.data.meta.status == 200) {
              // let temp = []
              // res.data.data.forEach(item=>{
              //   item.attr_vals=item.attr_vals?item.attr_vals.split(' '):[]
              // })
              this.tab3Data = res.data.data;
              console.log(this.tab3Data);
            } else {
              this.$message.error("获取失败");
              return;
            }
          })
          .catch(err => err);
      }
    },
    //图片上传成功后的操作
    handleSuccess(res) {
      this.formData.pics.push({ pic: res.data.tmp_path });
    },
    //移除图片
    handleRemove(file) {
      let path = file.response.data.tmp_path;
      let i = this.formData.pics.findIndex(item => {
        return item.pic == path;
      });
      this.formData.pics.splice(i, 1);
      console.log(this.formData.pics);
    },
    //图片预览
    handlePreview(file) {
      // console.log("22222");
      this.previewPath = file.response.data.url;
      this.previewVisible = true;
    },
    //添加商品
    addGood() {
      this.$refs.formRef.validate(valid => {
        if (!valid) {
          this.$message.warning("请填写必填信息");
          return;
        } else {
          //首先复制原表但的数据 在对其进行处理
          let selectedIdArr = { ...this.formData };
          delete selectedIdArr.selectedCates;
          // good_cat来存放商品分类的id
          selectedIdArr.goods_cat = this.formData.selectedCates;
          selectedIdArr.goods_cat = selectedIdArr.goods_cat.join(",");
          //存放only和many数据
          selectedIdArr.attrs = [];
          //定义一个收集数组的函数

          mergeArr(this.tab2Data, selectedIdArr);
          mergeArr(this.tab3Data, selectedIdArr);
          //发起添加商品请求
          console.log(selectedIdArr, this.tab2Data);
          this.$http
            .post("goods", selectedIdArr)
            .then(res => {
              if (res.data.meta.status == 201) {
                console.log(res.data);
                this.$message.success("添加商品成功");
                this.$router.push("/home/goods");
              } else {
                console.log(res.data);
                this.$message.error("添加商品失败");
              }
            })
            .catch(err => err);
        }
        function mergeArr(arr, sel) {
          arr.forEach(item => {
            let arrs = { attr_id: item.attr_id, attr_value: item.attr_vals };
            sel.attrs.push(arrs);
          });
        }
      });
    }
  },
  props: {
    test: String,
    activeIndex: {
      type: String,
      default() {
        return "0";
      }
    },
    labels: {
      type: Array,
      default() {
        return [];
      }
    },
    formData: {
      type: Object,
      default() {
        return {};
      }
    },
    formRules: {
      type: Object,
      default() {
        return {};
      }
    },
    casData: {
      type: Array,
      default() {
        return [];
      }
    },
    casProps: {
      type: Object,
      default() {
        return {};
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.desc {
  text-align: center;
  .add-good {
    margin-top: 20px;
  }
}
</style>
